//
//  SSPTabsCell.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/30.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "SSPTabsCell.h"

@interface SSPTabsCell ()

/// viewModle
@property (nonatomic, readwrite, strong) SSPTabsCellModel *viewModel;

/// IBOutlet
@property (weak, nonatomic) IBOutlet UIButton* commentTabBtn;
@property (weak, nonatomic) IBOutlet UIButton* zanTabBtn;
@property (weak, nonatomic) IBOutlet UIView* blockView;

@end

@implementation SSPTabsCell

- (void)awakeFromNib
{
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

#pragma mark - bind data
- (void)bindViewModel:(SSPTabsCellModel *)viewModel
{
    if (self.viewModel)
        return;
    
    self.viewModel = viewModel;
    
    @weakify(self);
    
    RACSignal* commentSignal = [[self.commentTabBtn rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value)
    {
        return @0;
    }];
    
    RACSignal* zanSignal = [[self.zanTabBtn rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value)
    {
        return @1;
    }];
    
    RAC(self.viewModel, tabIndex) = [RACSignal merge:@[commentSignal, zanSignal]];
    
    RACSignal* tabIndexChangeSignal = RACObserve(self.viewModel, tabIndex);
    RAC(self.commentTabBtn, enabled) = [[tabIndexChangeSignal replay] map:^id(id value) {
        
        NSInteger curTabIndex = [value integerValue];
        
        return @(curTabIndex != 0);
    }];
    RAC(self.zanTabBtn, enabled) = [[tabIndexChangeSignal replay] map:^id(id value) {
        
        NSInteger curTabIndex = [value integerValue];
        
        return @(curTabIndex != 1);
    }];
    
    [[tabIndexChangeSignal replay] subscribeNext:^(id x)
    {
        @strongify(self);
        
        NSInteger curTabIndex = [x integerValue];
        
        NSArray* tabBtns = @[self.commentTabBtn, self.zanTabBtn];
        
        UIButton* curTabBtn = tabBtns[curTabIndex];
        
        @weakify(self);
        [UIView animateWithDuration:0.2f animations:^
        {
            @strongify(self);
            
            self.blockView.centerX = curTabBtn.centerX;
        }];
    }];
    
    [[RACObserve(self.viewModel.data, praiseCount) deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSString* strPraise = HCStrFormat(@"点赞 %d", [x intValue]);
         
         [self.zanTabBtn setTitle:strPraise forState:UIControlStateNormal];
     }];
    
    [[RACObserve(self.viewModel.data, commentCount) deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSString* strComment = HCStrFormat(@"评论 %d", [x intValue]);
         
         [self.commentTabBtn setTitle:strComment forState:UIControlStateNormal];
     }];
}

@end
